package fr.alma.domo.music.impl;

import java.util.ArrayList;
import java.util.List;

import fr.alma.domo.model.AbstractService;
import fr.alma.domo.model.Resource;
import fr.alma.domo.model.Watcher;
import fr.alma.domo.music.ClientContext;
import fr.alma.domo.music.PositionControlService;
import fr.alma.domo.music.PositionService;
import fr.alma.domo.music.rc.HP;
import fr.alma.domo.util.Log;

@SuppressWarnings("serial")
public class PositionControlServiceImpl extends AbstractService implements
		PositionControlService {

	public PositionControlServiceImpl(){
		super("PositionControlService");
	}
	
	@Override
	public void startPositionControlLoop(){
		while(true){
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
			}
		}
	}
	
	
	@Watcher(scope=ClientContext.RESOURCE_FAMILY,property=ClientContext.POSITION)
	public static void onPositionChange(Resource r,String property,Object oldValue,Object newValue){
		Log.i(PositionControlService.class.getName()+"#PositionChange", "[%s] move from '%s' to '%s'",r.getAttribute(ClientContext.CLIENT_NAME,String.class),oldValue,newValue);
		if(newValue!=null 
				&& !PositionService.NO_POSITION.equals(newValue))
		{
			ClientContext ctx = (ClientContext)r;
			List<HP> list = new ArrayList<HP>(ctx.getHPs()); 
			for(HP hp : list){
				if(!newValue.equals(hp.getPosition())){
					//On essai de transferer le son vers la nouvelle location
					hp.transferSoundTo((String)newValue);
					//HP devient libre
					hp.setBusy(false);
				}
			}
			//De nouveaux HP on été crée a la nouvelle localisation on enleve donc les anciens
			for(HP hp : list){
				if(!newValue.equals(hp.getPosition())){
					ctx.getHPs().remove(hp);
				}
			}
		}
	}
	
}
